<template>
  <a-drawer :title="labelTitle" width="100%" :visible="modalVisible"
    :body-style="{ paddingBottom: '100px', paddingRight: '20px' }" @close="handleCancel">
    <splitpanes class="default-theme" @resize="resize" @resized="resized">
      <pane min-size="25" size="40">
        <a-form-model ref="caseHandleDecisionBase" :rules="rules" :model="infoForm" style="margin: 20px 20px">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="案由" prop="cause" >
          <a-textarea
            v-model="infoForm.cause"
            allow-clear
            :maxLength="3000"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入案由"
            @blur="previewDecisionDoc"
          />
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="决定事由" prop="reason" >
          <a-textarea
            v-model="infoForm.reason"
            allow-clear
            :maxLength="3000"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入决定事由"
            @blur="previewDecisionDoc"
          />
        </a-form-model-item>
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="根据" prop="according" >
          <a-textarea
            v-model="infoForm.according"
            allow-clear
            :maxLength="3000"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入根据"
            @blur="previewDecisionDoc"
          />
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="申请意见" prop="describe" >
          <a-textarea
            v-model="infoForm.describe"
            allow-clear
            :maxLength="3000"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入申请意见"
            @blur="previewDecisionDoc"
          />
        </a-form-model-item>
      </a-form-model>
    </pane>
      <pane min-size="25">
        <div class="pane_right">
          <div ref="file" :loading="previewLoading" element-loading-text="拼命加载中" 
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" 
            style="height:60%;overflow-y:auto;">
          </div>
        </div>
      </pane>
    </splitpanes>

    <div class="button-div">
      <a-button style="margin-right: 20px" @click="handleCancel"> 取消 </a-button>
      <a-button type="primary" icon="save" @click="onSubmit" :loading="loading"> 提交 </a-button>
    </div>
  </a-drawer>  

</template>
<script>
import { startBusinessProced, previewDecisionDoc } from '@/api/accept/business_Approve'
import { Tp_decision } from '@/enumeration/Tp_decision'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { renderAsync } from 'docx-preview'
import {CaseHandleDecisionMixin} from  '@/views/handleCase/CaseHandleDecisionMixin'
export default {
  mixins: [CaseHandleDecisionMixin],
  data() {
    return {
      infoForm: {
        applyid: '', // applyid
        proctype: '', // 操作分类
        userid: '',
        username: '',
        processinstanceid: '',
        cause: '', // 案由
        describe: '', // 行政复议申请
        reason: '', // 依据事由
        // 根据
        according:
          '《中华人民共和国行政复议法》第（xxx）条或者《中华人民共和国行政复议法实施条例》第xxxx条第xxxx款第（xxx）项的规定',
      },
      rules: {
        cause: [
          { required: true, message: '请输入案由', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        describe: [
          { required: true, message: '请输入申请意见', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        reason: [
          { required: true, message: '请输入依据事由', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
        according: [
          { required: true, message: '请输入根据', trigger: 'blur' },
          { max: 3000, message: '长度不能超过3000', trigger: 'blur' },
        ],
      },
      Tp_decision: Tp_decision,
      isResize: false,
      previewFileSrc: '',
      previewLoading:false,
    }
  },
  created() {},
  watch: {
    'infoForm.reason': {
      handler: function(newVal, oldVal) {
        // 当前的类型是公民类型
        this.infoForm.describe = "决定事由： " + newVal + "\n" + "根据： " + this.infoForm.according
        if (this.$refs.caseHandleStop) {
          this.$refs.caseHandleStop.validate()
        }
      },
      deep: true
    },
    'infoForm.according': {
      handler: function(newVal, oldVal) {
        // 当前的类型是公民类型
        this.infoForm.describe = "决定事由： " + this.infoForm.reason + "\n" + "根据：" + newVal
        if (this.$refs.caseHandleStop) {
          this.$refs.caseHandleStop.validate()
        }
      },
      deep: true
    }
  },

  components: {
    Splitpanes,
    Pane,
  },
  methods: {
    init() {
      this.modalVisible = true
      this.resetForm()
      this.infoForm.cause = this.reason;
      this.labelTitle = this.Tp_decision[this.decisiontype].name
      this.$nextTick(() => {
        this.previewDecisionDoc()
      })
    },
    handleCancel() {
      this.resetForm()
      this.modalVisible = false
    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.caseHandleDecisionBase.resetFields()
      })
    },
    /**
     * 提交表单
     */
    onSubmit() {
      this.$refs.caseHandleDecisionBase.validate((valid) => {
        this.loading = true
        if (valid) {
          console.log('submit!', this.infoForm)
          let params = {
            applyid: this.applyid, // applyid
            proctype: this.proctype, // 操作分类
            userid: this.currentUser.userId,
            username: this.currentUser.fullname,
            processinstanceid: this.processinstanceid, // 流程实例id
            cause: this.infoForm.cause, // 案由
            describe: this.infoForm.describe, // 行政复议申请
          }
          let docfield = {
            decisiontype: this.decisiontype, // 决定类型
            reason: this.infoForm.reason, // 依据事由
            according: this.infoForm.according, // 根据
          }
          console.log('入参参数：' + params)
          startBusinessProced(params, docfield).then((res) => {
            if (res.code !== 0) {
              this.$message.error('操作失败')
            } else {
              this.$message.success('操作成功')
              this.$emit('reload')
              this.$emit('close')
              this.modalVisible = false
              this.autoToSonRouter(res.data)
            }
            this.loading = false
          })
        } else {
          this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },

    resize() {
      this.isResize = true
    },
    resized() {
      this.isResize = false
    },
    previewDecisionDoc() {
      let _this = this
      let params = {
        applyid: _this.applyid, // applyid
        proctype: _this.proctype, // 操作分类
        userid: _this.currentUser.userId,
        username: _this.currentUser.fullname,
        processinstanceid: _this.processinstanceid, // 流程实例id
        cause: _this.infoForm.cause, // 案由
        describe: _this.infoForm.describe, // 行政复议申请
      }
      let docfield = {
        decisiontype: _this.decisiontype, // 决定类型
        reason: _this.infoForm.reason, // 依据事由
        according: _this.infoForm.according, // 根据
      }
      console.log('入参参数：' + params)
      this.previewLoading=true
      previewDecisionDoc(params, docfield).then((res) => {
        this.previewLoading=false
        renderAsync(res, this.$refs.file, null, {
          className: 'text-docx', //class name/prefix for default and document style classes
          inWrapper: true, //enables rendering of wrapper around document content
          ignoreWidth: false, //disables rendering width of page
          ignoreHeight: false, //disables rendering height of page
          ignoreFonts: false, //disables fonts rendering
          breakPages: true, //enables page breaking on page breaks
          ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
          experimental: true, //enables experimental features (tab stops calculation)
          trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
          useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
          useMathMLPolyfill: true, //includes MathML polyfills for chrome, edge, etc.
          debug: false //enables additional logging
        }) // 渲染到页面
      })
    }
  },
}
</script>
        
<style lang="scss" scoped>
  .button-div {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e9e9e9;
    padding: 10px 16px;
    background: #fff;
    text-align: center;
    z-index: 1
  }

</style>
            